#--===auroraplugin===--
#  -*- coding: utf-8 -*-
#  aurora plugin
#  usersearch_plugin.py
#  edited by kf (kforkingfisher@gmail/nimbuzz.com)
#############################################
###########    ##    #####         ##########
############  ###  #######  #####  ##########
############  ##  ########  #################
############  #  #########  #################
############    ##########  #### ############
############   ###########       ############
############    ##########  #### ############
############  #  #########  #################
############  ##   #######  #################
############  ###   ######  #################
###########    ##     ###    ################
#############################################
###########KFORKINGFISHER@GMAIL.COM##########
##########KFORKINGFISHER@NIMBUZZ.COM#########
#############################################


USERSEACH={'user':None}
USERSEACHCON=None



def userseach_start(type, source, parameters):
	global USERSEACH
	parameters=parameters.strip()
	if parameters:
		if USERSEACH['user']:
			reply(type,source,u'На данный момент я выполняю другой запрос. Попробуйте повторить через 5 минут.')
			return
		if type=='public':
			reply(type,source,u'Результат смотри у себя в привате через 3 минуты...')
		else:
			reply(type,source,u'Подожди 3 минутки...')
		
		USERSEACH=	{'user':'processed',
					'wrk':None,
					'k':0,
					's':0,
					'r':0,
					'result':[],
					'rooms':0,
					'rooms2':0,
					'users':0}
		parameters,i,nick=parameters.split(' '),0,[]
		
		for line in parameters:
			if line[0] == '-':
				line=line.lower()
				if line.count('k'):
					USERSEACH['k']=1
				if line.count('r'):
					USERSEACH['r']=1
				if line.count('s'):
					USERSEACH['s']=1
				p=line.replace('k','').replace('r','').replace('s','').replace('-','')
				if p:
					reply(type,source,u'Ключ "'+p+u'" не опознан. Останов.\nКлючи:\n r - игнор регистра\n k - игнор схожих по написанию символов\n s - нестрогое совпадение')
					USERSEACH['user']=None
					return
			else:
				nick.append(line)
		
		USERSEACH['user']=' '.join(nick)
		USERSEACH['wrk']=USERSEACH['user']
		
		if USERSEACH['r']:
			USERSEACH['wrk']=USERSEACH['wrk'].lower()
		if USERSEACH['k']:
			USERSEACH['wrk']=userseach_remove_kir(USERSEACH['wrk'])
		
		if not userseach_connect():
			reply(type,source,u'Ошибка подключения. Останов.')
			USERSEACH['user']=None
			return
		
		userseach_serverdisco()
		threading.Timer(170,userseach_finish,(source,)).start()

		
	else:
		reply(type,source,u'ииии?')
		return

def userseach_connect():
	try:
		jid='userseach-bot@jabber.ru' 
		password='2jcs01n4l7no9r'
		user=jid.split('@')[0]
		serv=jid.split('@')[1]
		global USERSEACHCON
		cn=xmpp.Client(server=serv, port=5222, debug=[])
		con=cn.connect(secure=0,use_srv=True)
		if not con:
			return 0
		auth=cn.auth(user, password, 'seacher')
		if not auth:
			return 0
	
		cn.sendInitPresence()
		USERSEACHCON=cn
		threading.Thread(None,userseach_reactor).start()
		return 1
	except:
		return 0
	
def userseach_reactor():
	global USERSEACH, USERSEACHCON
	while USERSEACH['user']:
		USERSEACHCON.Process(10)
	try:
		USERSEACHCON.disconnected()
	except:
		pass
	USERSEACHCON=None
		
		
def userseach_finish(source):
	if len(USERSEACH['result']):
		rep=u'Пользователь с никнеймом ' + USERSEACH['user'] + u' сейчас находится в:\n '+'\n '.join(USERSEACH['result'])
	else:
		rep=u'Пользователь с никнеймом ' + USERSEACH['user'] + u' не найден.'
	
	rep+=u'\nВсего пользователей найдено: ' + str(USERSEACH['users'])+ u'\nКонференций: '+str(USERSEACH['rooms'])+u' (из '+str(USERSEACH['rooms2'])+')'
	USERSEACH['user']=None
	reply('private',source,rep.strip())

def userseach_serverdisco(stop=None):
	server = 'conference.nimbuzz.com'
	iq = xmpp.Iq('get')
	id='s'+str(random.randrange(1, 9999999))
	iq.setID(id)
	query=iq.addChild('query', {}, [], xmpp.NS_DISCO_ITEMS)
	iq.setTo(server)
	USERSEACHCON.SendAndCallForResponse(iq, userseach_serverdisco_ans)


def userseach_serverdisco_ans(coze, res):
	global USERSEACH
	if res:
		if res.getType() == 'result':
			props=res.getQueryChildren()
			if not isinstance(props, list):
				return
			for x in props:
				att=x.getAttrs()
				if att.has_key('name'):
					USERSEACH['rooms2']+=1
					try:
						st=att['name'].split('(')[-1].split(')')[0]
						st=int(st)
					except:
						st=1
					if st:
						USERSEACH['rooms']+=1
						userseach_serverroom(att['jid'])


def userseach_serverroom(room):
	iq = xmpp.Iq('get')
	id='r'+str(random.randrange(1, 9999999))
	iq.setID(id)
	query=iq.addChild('query', {}, [], xmpp.NS_DISCO_ITEMS)
	iq.setTo(room)
	USERSEACHCON.SendAndCallForResponse(iq, userseach_serverroom_ans)
		
def userseach_serverroom_ans(coze, res):
	global USERSEACH
	if res:
		if res.getType() == 'result':
			props=res.getQueryChildren()
			if not isinstance(props, list):
				return
			for x in props:
				att=x.getAttrs()
				if att.has_key('name'):
					USERSEACH['users']+=1
					name=att['name'].strip()
					if USERSEACH['r']:
						name=name.lower()
					if USERSEACH['k']:
						name=userseach_remove_kir(name)
					if USERSEACH['s']:
						if name.count(USERSEACH['wrk']):
							USERSEACH['result'].append(res.getFrom().getStripped()+' ('+att['name']+')')
					else:
						if name == USERSEACH['wrk']:
							USERSEACH['result'].append(res.getFrom().getStripped()+' ('+att['name']+')')
					

def userseach_remove_kir(n):
	return n.replace(u'а', 'a').replace(u'А', 'A').replace(u'е', 'e').replace(u'Е', 'E').replace(u'Т', 'T').replace(u'о', 'o').replace(u'О', 'O').replace(u'р', 'p').replace(u'Р', 'P').replace(u'Н', 'H').replace(u'к', 'k').replace(u'К', 'K').replace(u'х', 'x').replace(u'Х', 'X').replace(u'с', 'c').replace(u'С', 'C').replace(u'В', 'B').replace(u'М', 'M').replace(u'У', 'Y').replace(u'у', 'y').replace(u'0', 'o')
		
		
		
register_command_handler(userseach_start, 'whereis', ['muc','all','info'], 0, 'search for a user on certain communities', 'whereis <jid>', ['whereis kforkingfisher','whereis kforkingfisher@nimbuzz.com'])